import { Node, Vec3 } from 'cc';
import { Vec3Util } from 'db://app-game/core/utils/Vec3Util';
import { ecs } from 'db://app-game/libs/ecs/ECS';
import { ECSEntity } from 'db://app-game/libs/ecs/ECSEntity';

/** 直线移动组件 */
@ecs.register('RectilinearMove')
export class RectilinearMoveComp extends ecs.Comp {
  /** 移动节点 */
  node: Node = null!;
  /** 移动方向 */
  velocity: Vec3 = new Vec3(0, 0, 0);
  /** 移动速度 (每秒移动的像素距离)*/
  speedOfMove: number = 0;
  /** 移动时间 */
  cTime: number = 0;
  /** 最大移动时间 */
  moveTime: number = 0;
  /** 移动完成回调 */
  onComplete: Function | null = null;

  reset(entity: ecs.Entity): void {
    this.node = null!;
    this.velocity = new Vec3(0, 0, 0);
    this.speedOfMove = 0;
    this.moveTime = 0;
    this.onComplete = null;
  }
}

/** 直线移动系统 */
@ecs.register('RectilinearMove')
export class RectilinearMoveSystem
  extends ecs.ComblockSystem<ecs.Entity>
  implements ecs.ISystemUpdate
{
  filter(): ecs.IMatcher {
    return ecs.allOf(RectilinearMoveComp);
  }
  update(entity: ECSEntity, dt: number): void {
    let move = entity.get(RectilinearMoveComp);
    move.cTime += dt;

    // 1. 如果移动时间大于最大移动时间，则移动完成
    if (move.cTime >= move.moveTime) {
      move.onComplete?.call(move);
      entity.remove(RectilinearMoveComp);
      return;
    }

    // 2. 如果移动时间小于最大移动时间，则移动
    let trans = Vec3Util.mul(move.velocity, move.speedOfMove * this.dt);
    move.node.translate(trans);
  }
}
